package cn.learn.wxlogin;

import cn.learn.base.BaseController;
import cn.learn.domain.module.Module;
import cn.learn.domain.system.user.User;
import cn.learn.domain.system.wxuser.WxUser;
import cn.learn.service.system.user.UserService;
import cn.learn.service.system.wxuser.WxUserService;
import cn.learn.utils.commons.MailUtils;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.mail.MessagingException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/wx")
public class WxLogin extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private WxUserService wxUserService;

    @RequestMapping(value = "/login", name = "用户微信扫码登录")
    public String login(String code) {
        WxUtil wxUtil = new WxUtil();
        // 获取用户登录认证
        Map<String, String> authorization = wxUtil.getAuthorization(code);
        System.out.println("authorization" + authorization);
        if (authorization.size() > 0) {
            // 用户授权登录
            String accessToken = authorization.get("access_token");

            String openId = authorization.get("openid");
            //得到用户信息
            WxUser wxUser = wxUserService.findUserByOpenId(openId);

            // 查询微信登录用户是否存在
            User userByWxOpenId = userService.findByWxOpenId(openId);
            request.setAttribute("wxOpenId", openId);
            request.setAttribute("accessToken", accessToken);
            if (userByWxOpenId == null || wxUser == null) {
                // 用户不存在, 则绑定
                return "login/bind";
                //判断用户是否验证
            }
            if ("1".equals(wxUser.getWxstatus())) {
                // 用户存在, 登录
                System.out.println(wxUser);
                String email = userByWxOpenId.getEmail();
                String password4DBWithWx = userByWxOpenId.getPassword();
                session.setAttribute("wxUser", wxUser);
                return "redirect:/login.do?email=" + email + "&password=" + password4DBWithWx;
            }else {
                request.setAttribute("error", "请先绑定您的邮箱!");
                return "login/bind";
            }
        }
        // 转发到绑定页面
        request.setAttribute("error", "微信授权异常!");
        return "login/bind";
    }

    /**
     * 用户微信登录绑定信息
     */
    @RequestMapping(value = "/wxBind", name = "用户微信登录绑定信息")
    public String wxBind(String wxOpenId, String email, String accessToken) throws InvocationTargetException, IllegalAccessException, MessagingException {
        // 绑定邮箱
        User userByEmail = userService.findByEmail(email);
        if (userByEmail != null) {
            // 用户存在
            userByEmail.setOpenid(wxOpenId);
            userService.updateOneByID(userByEmail);
            //获取用户信息并保存
            WxUtil wxUtil = new WxUtil();
            Map<String, String> userInfo = wxUtil.getUserInfo(accessToken, wxOpenId);
            WxUser wxUser = new WxUser();
            BeanUtils.populate(wxUser, userInfo);
            wxUser.setEmail(email);
            WxUser userByOpenId = wxUserService.findUserByOpenId(wxOpenId);
            if (userByOpenId==null) {
                wxUserService.save(wxUser);
            }else {
                wxUserService.upDateByUser(wxUser);

            }
                String emailMsg = wxOpenId;
                String content = "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3><a href='http://localhost/wx/wxbindSuccess.do?openId="
                        + emailMsg + "'>http://localhost/wx/wxbindSuccess.do?openId=" + emailMsg
                        + "</href></h3></body></html>";

                MailUtils.sendMail(email, content);
                session.setAttribute("user", userByEmail);
                String msg = "请前往邮箱进行激活";
                request.setAttribute("msg", msg);
                return "login/bind";
           /* }*/
        } else {
            // 用户不存在
            // 转发到绑定页面
            request.setAttribute("error", "绑定邮箱不存在, 请添加用户后再进行绑定");
            return "login/bind";
        }
    }

    @RequestMapping("/wxbindSuccess")
    public String wxBindSuccess(String openId) throws InvocationTargetException, IllegalAccessException {
        System.out.println("wxbindsuccess执行了");
        System.out.println(openId);
        WxUser userByOpenId1 = wxUserService.findUserByOpenId(openId);
        System.out.println(userByOpenId1);
        userByOpenId1.setWxstatus("1");
        wxUserService.upDateByUser(userByOpenId1);
        WxUser userByOpenId = wxUserService.findUserByOpenId(openId);
        String email = userByOpenId.getEmail();
        User byEmail = userService.findByEmail(email);
        String password = byEmail.getPassword();
        System.out.println("byEamil"+byEmail);

        session.setAttribute("wxUser", userByOpenId);
       request.setAttribute("email",email);
       request.setAttribute("password",password);
       return "login/jihuo";

    }


}
